package com.baiyue.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baiyue.entity.TollRules;
import com.baiyue.exception.GlobalException;
import com.baiyue.mapper.TollRulesMapper;
import com.baiyue.model.SelectOptionsResult;
import com.baiyue.model.tollRules.TollRulesDataRequest;
import com.baiyue.model.tollRules.TollRulesDataResponse;
import com.baiyue.result.CodeMsg;
import com.baiyue.service.TollRulesService;
import com.baiyue.utils.BeanMapperUtil;
import com.baiyue.utils.UserHolderUtil;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 计费规则
 * @author 伍波
 * @date 2024-04-30
 */
@Service
public class TollRulesServiceImpl implements TollRulesService {
    private static final Logger logger = LoggerFactory.getLogger(TollRulesServiceImpl.class);

    @Autowired
    private TollRulesMapper tollRulesMapper;

    /**
     * 新增计费规则
     * @param request
     */
    @Override
    public void insertTollRules(TollRulesDataRequest request){
        logger.info("新增计费规则入参：{}", JSONObject.toJSONString(request));
        //查询计费名称是否重复
        TollRules res = selectTollRules(request.getBillingName());
        if (Objects.nonNull(res)){
            logger.error("计费规则名称重复！！！");
            throw new GlobalException(CodeMsg.ALREADY_EXISTS.fillArgs("计费规则名称"));
        }
        if (Objects.isNull(request.getStatus())){
            request.setStatus(0);
        }
        TollRules tollRules = BeanMapperUtil.map(request, TollRules.class);
        tollRules.setCreateTime(new Date());
        tollRules.setUpdateTime(new Date());
        String user = UserHolderUtil.getUser().getUsername();
        tollRules.setCreateBy(user);
        tollRules.setUpdateBy(user);
        Integer result = tollRulesMapper.insert(tollRules);
        if (result <= 0){
            throw new GlobalException(CodeMsg.FAILURE);
        }
    }

    /**
     * 修改规则信息
     * @param request
     * @return
     */
    @Override
    public Boolean updateTollRules(TollRulesDataRequest request){
        logger.info("修改计费规则入参:{}", JSONObject.toJSONString(request));
        if (StringUtils.isNotEmpty(request.getBillingName())){
            TollRules res = selectTollRules(request.getBillingName());
            if (Objects.nonNull(res) && !Objects.equals(request.getId(), res.getId())){
                logger.error("计费规则名称重复！！！");
                throw new GlobalException(CodeMsg.ALREADY_EXISTS.fillArgs("计费规则名称"));
            }
        }
        String user = UserHolderUtil.getUser().getUsername();
        TollRules tollRules = BeanMapperUtil.map(request, TollRules.class);
        tollRules.setUpdateBy(user);
        tollRules.setUpdateTime(new Date());
        Integer result = tollRulesMapper.updateById(tollRules);
        return result >= 1;
    }

    /**
     * 批量删除
     * @param request
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteTollRules(TollRulesDataRequest request){
        logger.info("删除计费规则入参:{}", JSONObject.toJSONString(request));
        Objects.requireNonNull(request.getIds(), () -> {
            logger.error("删除计费规则失败：ids不可为空");
            return "删除计费规则失败：ids不可为空";
        });
        String user = UserHolderUtil.getUser().getUsername();
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("idList",request.getIds());
        paramMap.put("updateBy",user);
        Integer res = tollRulesMapper.deleteTollRulesByIds(paramMap);
        return res == request.getIds().size();
    }

    /**
     * 分页查询计费规则信息
     * @param request
     * @return
     */
    @Override
    public Page<TollRulesDataResponse> findByPage(TollRulesDataRequest request){
        logger.info("查询计费规则入参:{}", JSONObject.toJSONString(request));
        Page<TollRulesDataResponse> responsePage = new Page<>(request.getPage(),request.getSize());
        TollRules tollRules = BeanMapperUtil.map(request, TollRules.class);
        List<TollRules> resList = tollRulesMapper.findByPage(tollRules,responsePage);
        List<TollRulesDataResponse> resDataList = BeanMapperUtil.mapList(resList, TollRulesDataResponse.class);
        return responsePage.setRecords(resDataList);
    }

    /**
     * 根据id查询计费信息
     * @param request
     * @return
     */
    @Override
    public TollRulesDataResponse findById(TollRulesDataRequest request){
        logger.info("根据id查询计费规则入参:{}", JSONObject.toJSONString(request));
        if (Objects.isNull(request.getId())){
            throw new GlobalException(CodeMsg.BIND_ERROR.fillArgs("id"));
        }
        TollRules tollRules = tollRulesMapper.selectById(request.getId());
        return BeanMapperUtil.map(tollRules, TollRulesDataResponse.class);
    }
    /**
     * 根据计费规则名称查询计费规则信息
     * @param billingName
     * @return
     */
    public TollRules selectTollRules(String billingName){
        logger.info("根据计费名称查询计费规则信息入参:{}", billingName);
        if (StringUtils.isEmpty(billingName)){
            throw new GlobalException(CodeMsg.BIND_ERROR.fillArgs("billingName"));
        }
        return tollRulesMapper.findByBillingName(billingName);
    }

    @Override
    public List<SelectOptionsResult> selectOptions(){
        logger.info("获取计费规则下拉框");
        List<SelectOptionsResult> results = tollRulesMapper.findIdAndBillingName();
        if (results.isEmpty()){
            logger.warn("获取计费规则下拉列表失败");
            return null;
        }
        return results;
    }
}
